#app.py
from flask import Flask, request, jsonify
from flask_cors import CORS
import sqlite3
import hashlib

app = Flask(__name__)
CORS(app)  # 允许跨域

# 初始化数据库
def init_db():
    conn = sqlite3.connect('users.db')
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS users
                 (id INTEGER PRIMARY KEY AUTOINCREMENT,
                  first_name TEXT NOT NULL,
                  last_name TEXT NOT NULL,
                  phone TEXT UNIQUE NOT NULL,
                  password TEXT NOT NULL)''')
    conn.commit()
    conn.close()

# 密码加密
def encrypt_password(password):
    return hashlib.sha256(password.encode()).hexdigest()

# 用户注册接口
@app.route('/api/register', methods=['POST'])
def register():
    data = request.get_json()
    try:
        conn = sqlite3.connect('users.db')
        c = conn.cursor()
        
        # 检查手机号是否已存在
        c.execute("SELECT * FROM users WHERE phone=?", (data['phone'],))
        if c.fetchone():
            return jsonify({'success': False, 'message': '手机号已注册'}), 400
            
        # 插入新用户
        c.execute("INSERT INTO users (first_name, last_name, phone, password) VALUES (?, ?, ?, ?)",
                  (data['firstName'], data['lastName'], data['phone'], encrypt_password(data['password'])))
        conn.commit()
        return jsonify({'success': True, 'message': '注册成功'})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500
    finally:
        conn.close()

# 用户登录接口
@app.route('/api/login', methods=['POST'])
def login():
    data = request.get_json()
    try:
        conn = sqlite3.connect('users.db')
        c = conn.cursor()
        
        c.execute("SELECT * FROM users WHERE phone=? AND password=?",
                  (data['phone'], encrypt_password(data['password'])))
        user = c.fetchone()
        
        if user:
            return jsonify({
                'success': True,
                'data': {
                    'firstName': user[1],
                    'lastName': user[2],
                    'phone': user[3]
                }
            })
        else:
            return jsonify({'success': False, 'message': '手机号或密码错误'}), 401
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500
    finally:
        conn.close()

if __name__ == '__main__':
    init_db()
    app.run(host='0.0.0.0', port=5000, debug=True)